#include "comm.hpp"
int main()
{
    //1.创建共享内存的key值
    key_t k = ftok(PATH_NAME,PROJ_ID);
    assert(k != -1);
    Log("create key done",Debug) << " clinet key " << k << endl;

    //2.创建共享内存 -- 每一次创建都要是全新的共享内存
    int shmid = shmget(k,SHM_SIZE,0);
    if(shmid == -1)
    {
        perror("shmid:");
        exit(-1);
    }

    Log("create shmid done",Debug) << " clinet key " << k <<endl;
    //sleep(10);
    // 3.将指定的共享内存，挂接到自己的地址空间
    //第二个参数给空是让操作系统给我们随机分配共享内存地址
    char *shmaddr = (char*) shmat(shmid,nullptr,0);
    if(shmaddr == nullptr)
    {
        perror("shmaddr:");
        exit(-2);
    }
    Log("attach shm done",Debug) << " clinet key " << k << endl;
    //sleep(10);
    int fd = Openfifo(FIFO_NAME,WRITE);

    //进行通信
    while (true)
    {
        ssize_t s = read(0, shmaddr, SHM_SIZE - 1);
        if (s > 0)
        {
            shmaddr[s - 1] = 0;
            Singal(fd);//发信号
            if (strcmp(shmaddr, "quit") == 0) break;
        }
    }
    // char c = 'a';
    // for(;c <= 'c' ; c++)
    // {
    //     shmaddr[c - 'a'] = c;
    //     //我们是每一次都向shmaddr的共享内存的起始地址写入
    //     // snprintf(shmaddr,SHM_SIZE,"我是其他进程，我的pid:%d, inc：%c\n",getpid(),c);
    //     sleep(5);
    // }

    // strcpy(shmaddr,"quit");
    // 4.将指定的共享内存，从我们自己的地址空间中去关联
    int n = shmdt(shmaddr);
    assert( n != -1);
    (void)n;
    Log("derach shm done",Debug) << " clinet key " << k <<endl;
    //sleep(10);
    CloseFifo(fd);

    return 0;
}